package com.smart.mip.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.smart.mip.system.dao.UserInfoRepository;
import com.smart.mip.system.dao.UserRoleRepository;
import com.smart.mip.system.entity.SecurityUser;
import com.smart.mip.system.entity.UserInfo;
import com.smart.mip.system.entity.UserRole;

public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Autowired
	private UserRoleRepository userRoleRepository;
	
	@Override
	public UserDetails loadUserByUsername(String username) {
		UserInfo userInfo = userInfoRepository.findUserInfoByLoginName(username);
		if (userInfo == null) {
			throw new UsernameNotFoundException("loginname is null");
		}
		List<UserRole> userRoles = userRoleRepository.findUserRoleByUserCode(userInfo.getUserCode());
		userInfo.setUserRoles(userRoles);
		SecurityUser securityUser = new SecurityUser(userInfo);
		Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
		authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return securityUser;
	}

}
